package com.mj.mafeed.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import com.mj.mafeed.R;
import com.mj.mafeed.widget.LoadingDialog;
import com.mj.mafeed.widget.MyGridView;
import com.mj.mafeed.bean.ForumTopicJSON;
import com.mj.mafeed.service.ForumTopicService;
import com.mj.mafeed.util.DateUtils;
import com.mj.mafeed.util.NetUtils;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.SimpleAdapter.ViewBinder;

/**
 * 资讯添加
 * @author zhaominglei
 * @date 2016-1-22
 * 
 */
public class ForumTopicAddActivity extends Activity implements OnClickListener {
	@SuppressWarnings("unused")
	private static final String TAG = ForumTopicAddActivity.class.getSimpleName();
	private ForumTopicService forumTopicService = new ForumTopicService();
	private final int IMAGE_TAKE = 0; //拍照
	private final int IMAGE_SELECT = 1; //从相册中选择
	private ImageView goHome;
	private MyGridView gridView; //添加图片视图
	private Bitmap bitmap; //导入临时图片
	private ArrayList<HashMap<String, Object>> imageItem = new ArrayList<HashMap<String,Object>>();
	private SimpleAdapter simpleAdapter;
	private Intent intent;
	private Uri uri;
	private String imagePath; //图片路径
	private String takeFileName; //拍照保存的文件名
	private List<String> imagePaths = new ArrayList<String>(); //图片路径列表
	private TextView addTxt; //发布
	private EditText contentTxt; //内容
	private String content; //内容
	private LoadingDialog loadingDialog; //加载框
	private ForumTopicJSON forumTopicJSON;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_forumtopic_add);
		init();
	}
	
	private void init() {
		goHome = (ImageView)findViewById(R.id.forumtopicadd_gohome);
		gridView = (MyGridView)findViewById(R.id.forumtopicadd_gridView);
		addTxt = (TextView)findViewById(R.id.forumtopicadd_add);
		contentTxt = (EditText)findViewById(R.id.forumtopicadd_content_edt);
		
		goHome.setOnClickListener(this);
		addTxt.setOnClickListener(this);
		loadingDialog = new LoadingDialog(this);
		//init addpic
		bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.addpic);
		HashMap<String,Object> map = new HashMap<String, Object>();
		map.put("itemImage", bitmap);
		imageItem.add(map);
		simpleAdapter = new SimpleAdapter(this, imageItem, R.layout.griditem_addpic, new String[]{ "itemImage" }, new int[]{ R.id.griditem_addpic });
		simpleAdapter.setViewBinder(new ViewBinder() {
			@Override
			public boolean setViewValue(View view, Object data,
					String textRepresentation) {
				if (view instanceof ImageView && data instanceof Bitmap) {
					ImageView imageView = (ImageView)view;
					imageView.setImageBitmap((Bitmap)data);
					return true;
				}
				return false;
			}
		});
		gridView.setAdapter(simpleAdapter);
		gridView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position,	long id) {
				if (imageItem.size() == 10) {//第一张为默认图片
					Toast.makeText(ForumTopicAddActivity.this, R.string.forumtopicadd_addpic_hint2, Toast.LENGTH_SHORT).show();
				} else {
					if(position == 0) { //点击加号图片位置为0
						showDialogBottom();
					} else {
						delpic(position);
					}
				}
			}
		});		
	}

	//移除图片
	private void delpic(final int position) {
		AlertDialog dialog = new AlertDialog.Builder(ForumTopicAddActivity.this)
		.setMessage("确认移除已添加的图片吗？")
		.setTitle("提示")
    	.setPositiveButton("确认", new DialogInterface.OnClickListener() {
    		@Override
    		public void onClick(DialogInterface dialog, int which) {
    			dialog.dismiss();
    			imageItem.remove(position);
    	        simpleAdapter.notifyDataSetChanged();
    	        imagePaths.remove(imagePath);
    	        imagePath = null;
    		}
    	})
    	.setNegativeButton("取消", new DialogInterface.OnClickListener() {
    		@Override
    		public void onClick(DialogInterface dialog, int which) {
    			dialog.dismiss();
    		}
    	}).create();
    	dialog.show();
	}
	
	private void showDialogBottom() {
		final String[] menuArray = new String[] { "拍照", "从相册中选择", "取消" };
		AlertDialog dialog = new AlertDialog.Builder(ForumTopicAddActivity.this).setItems(menuArray, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				if (which == 0) { //拍照
					takeFileName = DateUtils.format(new Date(), "yyyyMMddHHmmss")+".png";
					intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
					//设置拍照后的照片存储的路径
					intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(), takeFileName)));
					startActivityForResult(intent, IMAGE_TAKE);
				} else if (which == 1){ //从相册中选择
					intent = new Intent(Intent.ACTION_PICK, null);
					intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
					startActivityForResult(intent, IMAGE_SELECT);
				}
				dialog.dismiss();
			}
		}).create();
		Window window = dialog.getWindow();  
	    window.setGravity(Gravity.BOTTOM);  //设置dialog显示的位置  
	    window.setWindowAnimations(R.style.dialogBottom); //添加动画
	    dialog.show();
	    Display display = getWindowManager().getDefaultDisplay();
	    WindowManager.LayoutParams layoutParams = window.getAttributes();
        layoutParams.width = (int) (display.getWidth());
	    dialog.getWindow().setAttributes(layoutParams);
	}	
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.forumtopicadd_gohome:
			ForumTopicAddActivity.this.finish();
			break;
		case R.id.forumtopicadd_add:
			content = contentTxt.getText().toString();
			if (content == null || content.equals("")) {
				Toast.makeText(getApplicationContext(), R.string.forumtopicadd_content_hint, Toast.LENGTH_SHORT).show();
				return;
			}
			add(getApplicationContext(), v);
			break;
		default:
			break;
		}
	}

	private void add(Context context, View v) {
		addTxt.setClickable(false);
		
		forumTopicJSON = new ForumTopicJSON();
		forumTopicJSON.setContent(content);
		if (imagePaths != null && !imagePaths.isEmpty()) {
			List<ForumTopicJSON.ForumTopicImage> forumTopicImages = new ArrayList<ForumTopicJSON.ForumTopicImage>();
			for (String path : imagePaths) {
				File imageFile = new File(path);
				if (imageFile.exists()) {
					ForumTopicJSON.ForumTopicImage forumTopicImage = new ForumTopicJSON.ForumTopicImage();
					forumTopicImage.setImageFile(imageFile);
					forumTopicImages.add(forumTopicImage);
				}
			}
			forumTopicJSON.setForumTopicImages(forumTopicImages);
		}
		if (NetUtils.isConnected(getApplicationContext())) {
			loadingDialog.show();
			new ForumTopicAddAsyncTask().execute("");
		} else {
			Toast.makeText(getApplicationContext(), R.string.net_error, Toast.LENGTH_SHORT).show();
		}
	}

	@Override
	public void onBackPressed() {
		ForumTopicAddActivity.this.finish();
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case IMAGE_TAKE: //拍照
				File takeImageFile = new File(Environment.getExternalStorageDirectory(), takeFileName);
				if (takeImageFile.exists()) {
					imagePath = takeImageFile.getAbsolutePath();
				}
				break;
				
			case IMAGE_SELECT: //从相册中选择
				uri = data.getData();  
				if (!TextUtils.isEmpty(uri.getAuthority())) {
					//查询选择图片
					Cursor cursor = getContentResolver().query(
	                        uri,  
	                        new String[] { MediaStore.Images.Media.DATA },  
	                        null,   
	                        null,   
	                        null);
					//没找到图片 返回 
	                if (null == cursor) {  
	                    return;  
	                }
	                cursor.moveToFirst();
	                imagePath = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
				}
				break;

			default:
				break;
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	protected void onResume() {
		super.onResume();
		if(!TextUtils.isEmpty(imagePath)){
			imagePaths.add(imagePath);
			bitmap = BitmapFactory.decodeFile(imagePath);
			HashMap<String,Object> map = new HashMap<String, Object>();
			map.put("itemImage", bitmap);
			imageItem.add(map);
			simpleAdapter = new SimpleAdapter(this, imageItem, R.layout.griditem_addpic, new String[]{ "itemImage" }, new int[]{ R.id.griditem_addpic });
			simpleAdapter.setViewBinder(new ViewBinder() {
				@Override
				public boolean setViewValue(View view, Object data,
						String textRepresentation) {
					if (view instanceof ImageView && data instanceof Bitmap) {
						ImageView imageView = (ImageView)view;
						imageView.setImageBitmap((Bitmap)data);
						return true;
					}
					return false;
				}
			});
			gridView.setAdapter(simpleAdapter);
			simpleAdapter.notifyDataSetChanged();
		}
	}
	
	public class ForumTopicAddAsyncTask extends AsyncTask<String, String, Boolean> {
		@Override
		protected Boolean doInBackground(String... params) {
			return forumTopicService.save("ForumTopicAddActivity", forumTopicJSON);
		}

		@Override
		protected void onPostExecute(Boolean result) {
			loadingDialog.dismiss();
			if (result) {
				Toast.makeText(getApplicationContext(), R.string.save_success, Toast.LENGTH_SHORT).show();
				ForumTopicAddActivity.this.finish();
			} else {
				addTxt.setClickable(true);
				Toast.makeText(getApplicationContext(), R.string.save_error, Toast.LENGTH_SHORT).show();
			}
		}
	}
}
